package com.tgy.admin.Service.impl;

import cn.hutool.core.util.StrUtil;
import com.tgy.admin.Service.AdminArticleService;
import com.tgy.admin.util.BeanFieldUtils;
import com.tgy.core.service.BlogArticleService;
import com.tgy.core.service.BlogCommentService;
import com.tgy.files.service.impl.HtmlService;
import com.tgy.page.PageQuery;
import com.tgy.page.TableDataInfo;
import com.tgy.pojo.BlogArticle;
import com.tgy.pojo.BlogUser;
import com.tgy.result.GraceJSONResult;
import com.tgy.result.LayuiTableResult;
import com.tgy.vo.StatisticsVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author tianguiyin
 * @version 1.0
 * @date 2022/6/21 21:04
 *
 * 后台用户业务实现
 */
@Service
public class AdminArticleServiceImpl implements AdminArticleService {

    final static Logger logger = LoggerFactory.getLogger(AdminArticleServiceImpl.class);

    @Resource
    private BlogArticleService blogArticleService;
    @Resource
    private BlogCommentService blogCommentService;
    @Resource
    private BeanFieldUtils beanFieldUtils;
    @Resource
    private HtmlService htmlService;

    @Value("${tgy.articleImage}")
    private String articleImage;


    @Override
    public LayuiTableResult getBlogArticleList(BlogArticle bo, PageQuery pageQuery) {
        ArrayList<String> existFields = new ArrayList<>();
        existFields.add("content");
        bo.setExistFields(existFields);
        return blogArticleService.queryLayuiPageList(bo,pageQuery);
    }


    @Transactional
    @Override
    public GraceJSONResult addBlogArticle(BlogArticle bo) {
        try {
            beanFieldUtils.add(bo);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        bo.setWatchNumber(0);
        bo.setCommentNumber(0);

        // 设置默认图片
        if (StrUtil.isBlank(bo.getArticleCover())){
            bo.setArticleCover(articleImage);
        }

        // 添加文章到数据库
        Boolean aBoolean = blogArticleService.insertByBo(bo);


        //创建静态页面
        String articleGridFS = null;
        try {
            //直接生成html文件到指定位置
            //articleHtmlService.createArticleHTML(sysArticle.getId());
            //上传到GridFS，返回的是在GridFS中存储的id
            articleGridFS = htmlService.createArticleHTMLToGridFS(bo);

            //从GridFS中下载文章
            htmlService.download(bo.getId(),articleGridFS);
            logger.info("文章下载成功");
        }catch (Exception e){
            logger.error("文章上传失败",e);
            aBoolean = false;
            blogArticleService.deleteById(bo.getId());
            //上传成功了但是生成文件失败了就删除
            if (StringUtils.isNotBlank(articleGridFS)){
                htmlService.delete(bo.getId(),articleGridFS);
            }
            e.printStackTrace();
        }
        bo.setArticleGrid(articleGridFS);
        blogArticleService.updateByBo(bo);

        if (aBoolean){
            return GraceJSONResult.ok();
        }else {
            return GraceJSONResult.error();
        }
    }

    @Transactional
    @Override
    public GraceJSONResult updateBlogArticle(BlogArticle bo) {
        try {
            beanFieldUtils.update(bo);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        blogArticleService.updateByBo(bo);

        BlogArticle byId = blogArticleService.getById(bo.getId());
        // BeanUtil.copyProperties(bo,byId);
        // 删除静态页面和存储的
        Integer delete = htmlService.delete(byId.getId(),byId.getArticleGrid());

        String articleGridFS = null;
        if (delete == 200){
            try {
                //上传到GridFS，返回的是在GridFS中存储的id
                articleGridFS = htmlService.createArticleHTMLToGridFS(byId);
                //从GridFS中下载文章
                htmlService.download(byId.getId(),articleGridFS);
                logger.info("文章下载成功");
            }catch (Exception e){
                logger.error("文章上传失败",e);
                e.printStackTrace();
            }
        }

        byId.setArticleGrid(articleGridFS);
        blogArticleService.updateByBo(byId);

        if (StrUtil.isBlank(articleGridFS)){
            return GraceJSONResult.error();
        }else {
            return GraceJSONResult.ok();
        }
    }

    @Override
    public GraceJSONResult delBlogArticle(String id) {
        BlogArticle article = blogArticleService.getById(id);
        Boolean aBoolean = blogArticleService.deleteById(id);
        if (aBoolean){
            htmlService.delete(article.getId(),article.getArticleGrid());
        }
        return GraceJSONResult.ok();
    }

    @Override
    public GraceJSONResult delBlogArticleIds(List<String> ids) {
        for (String id : ids) {
            BlogArticle article = blogArticleService.getById(id);
            htmlService.delete(article.getId(),article.getArticleGrid());
        }
        blogArticleService.deleteWithValidByIds(ids, false);
        return GraceJSONResult.ok();
    }

    @Override
    public GraceJSONResult getBlogArticleById(String id) {
        return GraceJSONResult.ok(blogArticleService.queryById(id));
    }

    @Override
    public GraceJSONResult updateStatus(String id, Integer status) {
        int i = blogArticleService.updateStatus(id,status);
        if (i>0){
            return GraceJSONResult.ok();
        }else {
            return GraceJSONResult.error();
        }
    }

    @Override
    public StatisticsVo getStatisticsNumber() {
        return blogArticleService.getStatisticsNumber();
    }

    @Override
    public Map<String, Object> getArticleTopTen() {
        BlogArticle bo = new BlogArticle();
        PageQuery pageQuery = new PageQuery();
        pageQuery.setIsAsc("desc");
        pageQuery.setOrderByColumn("watchNumber");
        pageQuery.setLimit(5);
        TableDataInfo<BlogArticle> dataInfo = blogArticleService.queryPageList(bo, pageQuery);
        List<BlogArticle> rows = dataInfo.getRows();
        List<String> xData = rows.stream().map(BlogArticle::getTitle).collect(Collectors.toList());
        List<Integer> yData = rows.stream().map(BlogArticle::getWatchNumber).collect(Collectors.toList());

        Map<String,Object> map = new HashMap<>();
        map.put("xData",xData);
        map.put("yData",yData);

        return map;
    }

    @Override
    public Map<String, Object> getUserTopTen() {

        List<BlogUser> list = blogCommentService.getUserTopTen();

        List<String> xData = list.stream().map(BlogUser::getNickname).collect(Collectors.toList());
        List<Integer> yData = list.stream().map(BlogUser::getCommentNum).collect(Collectors.toList());

        Map<String,Object> map = new HashMap<>();
        map.put("xData",xData);
        map.put("yData",yData);
        return map;
    }

}
